﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QianBuo.Lottery.Web.Models;
using Code.Commen;
using Code.BLL;
using Code.Models;
using System.Text;
using QianBuo.Lottery.Web.Models.ChaseTask;
using QianBuo.Lottery.Web.Models.Scheme;

namespace QianBuo.Lottery.Web.Controllers
{
    public class ChaseTaskController : BaseController
    {
        //
        // GET: /ChaseTesk/


        #region 追号明细
        public ActionResult Index(ChaseModel model)
        {
            if (model == null)
                model = new ChaseModel();
            if (model.LotteryIDs == null || model.LotteryIDs.Count() == 0)
                model.LotteryIDs = CacheManage.Lottery.OrderBy(p => p.Value.ID).OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Selected = model.Search == null ? false : model.Search.LotteryID == p.Value.ID, Text = p.Value.Name, Value = p.Value.ID.ToString() });
            if (model.WinModels == null || model.WinModels.Count() == 0)
                model.WinModels = CacheManage.WinModel.Select(p => new SelectListItem { Selected = model.Search == null ? false : model.Search.WinModelID == p.Value.ID, Text = p.Value.Name, Value = p.Value.ID.ToString() });
            if (model.ConsumptionRatios == null || model.ConsumptionRatios.Count() == 0)
                model.ConsumptionRatios = CacheManage.Ratio.Select(p => new SelectListItem { Selected = model.Search == null ? false : model.Search.ConsumptionRatio == p.Value.Ratio, Text = p.Value.Name, Value = p.Value.Ratio.ToString() });
            var search = GetChaseWhere(model.Search);
            var data = new ChaseManage().ChaseTaskList(LoginUserID, search.Propertie1, search.Propertie2).ToList();
            if (model.pageInfo == null)
                model.pageInfo = new PageInfo();
            model.pageInfo.SunCount = data.Count;
            model.ChaseList = data.Skip((model.pageInfo.CurrPage - 1) * model.pageInfo.PageCount).Take(model.pageInfo.PageCount);
            if (model.Search == null)
                model.Search = new DefaultModel.Where();
            if (model.ChaseList == null)
                model.ChaseList = new List<ChaseTask>();
            return View(model);
        }
        private Key<string, object[]> GetChaseWhere(DefaultModel.Where search)
        {
            var sql = " 1==1 ";
            var paramList = new List<object>();
            if (search == null)
                return new Key<string, object[]>(sql, paramList.ToArray());
            if (search.ConsumptionRatio.HasValue)
            {
                sql += " and ConsumptionRatio=@" + paramList.Count;
                paramList.Add(search.ConsumptionRatio.Value);
            }
            if (search.LotteryID.HasValue)
            {
                sql += " and LotteryID=@" + paramList.Count;
                paramList.Add(search.LotteryID.Value);
            }
            if (search.State.HasValue)
            {
                sql += " and State=@" + paramList.Count;
                paramList.Add(search.State.Value);
            }
            if (search.WinModelID.HasValue)
            {
                sql += " and WinModelID=@" + paramList.Count;
                paramList.Add(search.WinModelID.Value);
            }
            return new Key<string, object[]>(sql, paramList.ToArray());
        }
        public ActionResult NumberList(string str)
        {
            var CM = new ChaseManage();
            var playList = CacheManage.Playlist.ToDictionary(p => p.Value.ID, p => p.Value.Name);
            var plays = CM.ParseChaseTaskNumber(str).Select(p => new ChaseNumberModel
                {
                    PlayTypeName = playList[p.PlayListID],
                    Number = p.Number,
                    Count = p.Count,
                    Money = p.SingleMoney,
                    BackMoneyToWinMoney = p.BackMoneyToWinMoney * 100,
                });
            
            return View("NumberList", plays);
        }

        public ActionResult Detail(ChaseDetailModel model)
        {
            if (!ModelState.IsValid)
                return RedirectToAction("Index");

            var CM = new ChaseManage();
            var data = CM.ChaseTaskDetailList(LoginUserID, model.ChaseID.Value);
            model.ChaseTask = CM.GetChaseTasks(null, LoginUserID).FirstOrDefault(p=>p.ID==model.ChaseID.Value);
            if (model.ChaseTask != null)
            {
                model.ChaseTask.WinModelName = CacheManage.WinModel[model.ChaseTask.WinModel].Name;
                model.ChaseTask.RatioName = CacheManage.Ratio[model.ChaseTask.Ratio].Name;
            }
            if (model.pageInfo == null)
                model.pageInfo = new PageInfo();
            model.pageInfo.SunCount = data.Count();
            model.DetailList = data.Skip((model.pageInfo.CurrPage - 1) * model.pageInfo.PageCount).Take(model.pageInfo.PageCount).ToArray();
            model.DetailList.Each(p=>p.IssueNumber=Issue.PastIssueName(model.ChaseTask.LotteryType,p.IssueNumber));
            return View(model);
        }
        /// <summary>
        /// 撤消追号明细
        /// </summary>
        /// <param name="ID">追号明细ID</param>
        /// <returns></returns>
        public JsonResult QuashChaseOrder(long? ID)
        {
            var msg = string.Empty;
            var result = -1;
            if (ID.HasValue)
            {
                try
                {
                    result = new ChaseManage().CancelDetail(ID.Value, ChaseTaskState.UserCancel);
                    if (result > 0)
                    {
                        msg = "已成功撤消！";
                    }
                    else
                        msg = "操作失败！请稍后重新操作。";
                }
                catch (ValidateException e)
                {
                    msg = e.Message;
                }
                catch (AppException e1)
                {
                    msg = e1.Message;
                }
                catch (Exception e2)
                {
                    msg = "操作失败！请稍后重新操作。";
                    if (Log.IsDebugEnabled)
                        Log.Debug("撤消追号明细操作失败！ID:" + ID.Value, e2);
                    if (Log.IsWarnEnabled)
                        Log.Warn("撤消追号明细操作失败！ID:" + ID.Value);
                }
            }
            return Json(new { Msg = msg, Result = result }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 撤消追号任务
        /// </summary>
        /// <param name="ID">追号明细ID</param>
        public ActionResult QuashChaseTask(Guid ID)
        {
            var red = Request["returnurl"] ?? Url.Action("Index");
            var msg = string.Empty;
            var result = -1;
            try
            {
                var cm = new ChaseManage();
                var flag = cm.Select(s => s.Any(p => p.ID == ID && p.UserID == LoginUserID));
                if (!flag)
                    msg = "不存在该任务";
                else
                {
                    result = cm.CancelTask(ID, ChaseTaskState.UserCancel);
                    if (result > 0)
                    {
                        msg = "已成功中止！";
                    }
                    else
                        msg = "操作失败！请稍后重新操作。";
                }
            }
            catch (AppException e)
            {
                msg = e.Message;
            }
            catch (Exception)
            {
                msg = "操作失败！请稍后重新操作。";
            }

            return Content(string.Format("<script>alert('{0}');location.href='{1}';</script>", msg, red));
        }
        #endregion
    }
}
